"use client"

import { useState, useEffect } from "react"
import { useRouter, useSearchParams } from "next/navigation"
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { Badge } from "@/components/ui/badge"
import { Skeleton } from "@/components/ui/skeleton"
import { Separator } from "@/components/ui/separator"
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select"
import {
  ArrowLeft,
  TrendingUp,
  TrendingDown,
  Activity,
  Target,
  BarChart3,
  AlertCircle,
  CheckCircle2,
  RefreshCw,
  ChevronDown,
  ChevronUp,
  Calendar,
  DollarSign,
  Percent,
  Volume2
} from "lucide-react"
import { getStockDailyTracking, getStockCycles, StockTrackingData, DailyRecord, SignalDistribution, ObservationCycle } from "@/lib/api/tracking"
import { useApiCall } from "@/lib/hooks/use-api-call"
import { useToast } from "@/hooks/use-toast"
import { cn } from "@/lib/utils"
import { ThemeSwitch } from "@/components/theme-switch"
import { UserNav } from "@/components/user-nav"

/**
 * 格式化百分比
 */
const formatPercent = (value: number, showSign = true) => {
  const sign = showSign && value > 0 ? '+' : ''
  return `${sign}${value.toFixed(2)}%`
}

/**
 * 格式化价格
 */
const formatPrice = (price: number) => {
  return `¥${price.toFixed(2)}`
}

/**
 * 格式化成交量
 */
const formatVolume = (volume: number) => {
  if (volume >= 100000000) {
    return `${(volume / 100000000).toFixed(2)}亿`
  }
  if (volume >= 10000) {
    return `${(volume / 10000).toFixed(1)}万`
  }
  // 小于1万时，直接显示数值（可能单位是万手）
  return `${volume.toFixed(1)}万`
}

/**
 * 单日记录卡片组件
 */
function DailyRecordCard({ record, index }: { record: DailyRecord; index: number }) {
  const [expanded, setExpanded] = useState(false)
  const isProfit = record.dailyReturn >= 0
  const borderColor = isProfit ? "border-l-success" : "border-l-destructive"
  // 只在深色主题下显示背景色，浅色主题下不显示（与主页面卡片风格一致）
  const bgColor = isProfit ? "dark:bg-success/10" : "dark:bg-destructive/10"

  return (
    <Card className={cn("border-l-4 transition-all", borderColor, bgColor)}>
      <CardContent className="p-4">
        {/* 基础信息行 */}
        <div className="flex items-center justify-between mb-3">
          <div className="flex items-center space-x-3">
            <Badge variant="outline" className="text-xs font-mono">
              Day {record.days}
            </Badge>
            <div className="flex items-center text-sm text-muted-foreground">
              <Calendar className="w-3 h-3 mr-1" />
              {record.date}
            </div>
            <Badge variant={record.isEnd ? "secondary" : "default"} className="text-xs">
              {record.status}
            </Badge>
          </div>

          <Button
            variant="ghost"
            size="sm"
            onClick={() => setExpanded(!expanded)}
            className="h-8 w-8 p-0"
          >
            {expanded ? <ChevronUp className="w-4 h-4" /> : <ChevronDown className="w-4 h-4" />}
          </Button>
        </div>

        {/* 核心数据网格 */}
        <div className="grid grid-cols-2 md:grid-cols-4 gap-3 mb-3">
          {/* 当日收益 */}
          <div>
            <p className="text-xs text-muted-foreground mb-1">当日收益</p>
            <p className={cn(
              "text-base font-bold font-mono",
              isProfit ? "text-success" : "text-destructive"
            )}>
              {formatPercent(record.dailyReturn)}
            </p>
          </div>

          {/* 累计收益 */}
          <div>
            <p className="text-xs text-muted-foreground mb-1">累计收益</p>
            <p className={cn(
              "text-base font-bold font-mono",
              record.cumulativeReturn >= 0 ? "text-success" : "text-destructive"
            )}>
              {formatPercent(record.cumulativeReturn)}
            </p>
          </div>

          {/* 买入价 */}
          <div>
            <p className="text-xs text-muted-foreground mb-1">买入价</p>
            <p className="text-base font-medium font-mono">
              {formatPrice(record.buyPrice)}
            </p>
          </div>

          {/* 收盘价 */}
          <div>
            <p className="text-xs text-muted-foreground mb-1">收盘价</p>
            <p className="text-base font-medium font-mono">
              {formatPrice(record.closePrice)}
            </p>
          </div>
        </div>

        {/* 成交量信息 */}
        <div className="flex items-center justify-between text-xs">
          <div className="flex items-center space-x-4">
            <div className="flex items-center">
              <Volume2 className="w-3 h-3 mr-1 text-muted-foreground" />
              <span className="text-muted-foreground">成交量:</span>
              <span className="ml-1 font-mono font-medium">{formatVolume(record.volume)}</span>
            </div>
            <div>
              <span className="text-muted-foreground">量比:</span>
              <span className="ml-1 font-mono font-medium">{record.volumeRatio.toFixed(2)}</span>
            </div>
          </div>
          <Badge variant={record.volumeChange.includes('放量') ? "default" : "secondary"} className="text-xs">
            {record.volumeChange}
          </Badge>
        </div>

        {/* 展开详情 */}
        {expanded && (
          <>
            <Separator className="my-3" />
            <div className="space-y-3">
              {/* 信号信息 */}
              <div className="bg-accent/10 rounded-lg p-3">
                <div className="flex items-center justify-between mb-2">
                  <p className="text-xs font-semibold text-accent">信号分析</p>
                  <Badge variant="outline" className="text-xs">
                    强度: {record.signalStrength.toFixed(2)}
                  </Badge>
                </div>
                <p className="text-xs text-muted-foreground mb-1">
                  信号数量: <span className="font-medium">{record.signalCount} 个</span>
                </p>
                <p className="text-xs">{record.signalReason}</p>
              </div>

              {/* 大盘对比 */}
              <div className="grid grid-cols-2 gap-3">
                <div className="bg-muted/50 rounded-lg p-3">
                  <p className="text-xs text-muted-foreground mb-1">大盘收益</p>
                  <p className="text-sm font-mono font-medium">
                    {formatPercent(record.marketIndexReturn)}
                  </p>
                  <p className="text-xs text-muted-foreground mt-1">{record.marketStatus}</p>
                </div>
                <div className="bg-muted/50 rounded-lg p-3">
                  <p className="text-xs text-muted-foreground mb-1">跑赢大盘</p>
                  <div className="flex items-center mt-1">
                    {record.outperformMarket ? (
                      <>
                        <CheckCircle2 className="w-4 h-4 text-success mr-1" />
                        <span className="text-sm font-medium text-success">是</span>
                      </>
                    ) : (
                      <>
                        <AlertCircle className="w-4 h-4 text-muted-foreground mr-1" />
                        <span className="text-sm font-medium text-muted-foreground">否</span>
                      </>
                    )}
                  </div>
                </div>
              </div>
            </div>
          </>
        )}
      </CardContent>
    </Card>
  )
}

/**
 * 统计指标卡片
 */
function StatCard({
  icon: Icon,
  title,
  value,
  description,
  valueColor
}: {
  icon: any
  title: string
  value: string | number
  description?: string
  valueColor?: string
}) {
  return (
    <Card>
      <CardContent className="p-4">
        <div className="flex items-center justify-between mb-2">
          <p className="text-sm text-muted-foreground">{title}</p>
          <Icon className="w-4 h-4 text-muted-foreground" />
        </div>
        <p className={cn("text-2xl font-bold font-mono", valueColor)}>
          {value}
        </p>
        {description && (
          <p className="text-xs text-muted-foreground mt-1">{description}</p>
        )}
      </CardContent>
    </Card>
  )
}

/**
 * 信号分布统计组件（卡片网格版 - 符合系统风格）
 */
function SignalDistributionCard({ signals }: { signals: SignalDistribution[] }) {
  if (!signals || signals.length === 0) {
    return null
  }

  // 按平均收益排序（从高到低）
  const sortedSignals = [...signals].sort((a, b) => b.avgReturn - a.avgReturn)

  // 获取胜率对应的颜色
  const getWinRateColor = (winRate: number) => {
    if (winRate >= 70) return "text-success"
    if (winRate >= 50) return "text-accent"
    return "text-muted-foreground"
  }

  const getWinRateIndicator = (winRate: number) => {
    if (winRate >= 70) return { color: "bg-success", label: "高效" }
    if (winRate >= 50) return { color: "bg-accent", label: "有效" }
    return { color: "bg-muted-foreground", label: "待观察" }
  }

  return (
    <Card>
      <CardHeader className="pb-4">
        <div className="flex items-center justify-between">
          <CardTitle className="text-base flex items-center gap-2">
            <Activity className="w-4 h-4 text-accent" />
            信号分布与有效性统计
          </CardTitle>
          <Badge variant="outline" className="text-xs">
            {signals.length} 种
          </Badge>
        </div>
      </CardHeader>
      <CardContent className="pt-0">
        {/* 迷你卡片网格 */}
        <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
          {sortedSignals.map((signal, index) => {
            const indicator = getWinRateIndicator(signal.winRate)
            return (
              <Card key={index} className="border-l-4" style={{ borderLeftColor: `hsl(var(--${indicator.color.replace('bg-', '')}))` }}>
                <CardContent className="p-3">
                  {/* 信号名称和标签 */}
                  <div className="flex items-start justify-between gap-2 mb-2">
                    <p className="text-sm font-medium leading-tight flex-1" title={signal.signalName}>
                      {signal.signalName}
                    </p>
                    <Badge variant="secondary" className="text-xs shrink-0">
                      {signal.appearanceCount}次
                    </Badge>
                  </div>

                  {/* 关键指标 */}
                  <div className="grid grid-cols-2 gap-3 text-xs">
                    {/* 平均收益 */}
                    <div>
                      <p className="text-muted-foreground mb-0.5">平均收益</p>
                      <p className={cn(
                        "text-base font-bold font-mono",
                        signal.avgReturn >= 0 ? "text-success" : "text-destructive"
                      )}>
                        {formatPercent(signal.avgReturn)}
                      </p>
                    </div>

                    {/* 胜率 */}
                    <div>
                      <p className="text-muted-foreground mb-0.5">胜率</p>
                      <div className="flex items-baseline gap-1.5">
                        <p className={cn("text-base font-bold", getWinRateColor(signal.winRate))}>
                          {signal.winRate.toFixed(0)}%
                        </p>
                        <span className={cn("text-xs", getWinRateColor(signal.winRate))}>
                          {indicator.label}
                        </span>
                      </div>
                    </div>
                  </div>
                </CardContent>
              </Card>
            )
          })}
        </div>

        {/* 说明图例 */}
        <div className="mt-4 pt-3 border-t flex items-center justify-center gap-6 text-xs text-muted-foreground">
          <div className="flex items-center gap-1.5">
            <div className="w-2 h-2 rounded-full bg-success" />
            <span>高效 ≥70%</span>
          </div>
          <div className="flex items-center gap-1.5">
            <div className="w-2 h-2 rounded-full bg-accent" />
            <span>有效 50-70%</span>
          </div>
          <div className="flex items-center gap-1.5">
            <div className="w-2 h-2 rounded-full bg-muted-foreground" />
            <span>待观察 &lt;50%</span>
          </div>
        </div>
      </CardContent>
    </Card>
  )
}

/**
 * 股票每日跟踪页面
 */
export default function StockTrackingPage() {
  const router = useRouter()
  const searchParams = useSearchParams()
  const { toast } = useToast()
  
  // 从 URL 查询参数获取股票代码
  const stockCode = searchParams.get('code') || ''

  const [data, setData] = useState<StockTrackingData | null>(null)
  const [cycles, setCycles] = useState<ObservationCycle[]>([])
  const [selectedCycle, setSelectedCycle] = useState<ObservationCycle | 'ALL' | null>(null) // 选中的周期对象或"全部"
  const [initialLoading, setInitialLoading] = useState(true) // 追踪初始加载状态

  // 获取观察周期列表
  const { execute: fetchCycles, isLoading: cyclesLoading } = useApiCall(
    () => getStockCycles(stockCode),
    {
      showToast: false,
      autoRetry: true,
    }
  )

  // 获取每日跟踪数据（支持周期筛选或全部周期）
  const { execute: fetchTracking, isLoading } = useApiCall(
    () => {
      if (selectedCycle === 'ALL') {
        // 查询所有周期
        return getStockDailyTracking(stockCode, { allCycles: true })
      } else if (selectedCycle) {
        // 查询特定周期
        return getStockDailyTracking(stockCode, { 
          startDate: selectedCycle.startDate, 
          endDate: selectedCycle.endDate 
        })
      } else {
        // 无选择，默认查询
        return getStockDailyTracking(stockCode)
      }
    },
    {
      showToast: false,
      autoRetry: true,
    }
  )

  // 加载观察周期列表并返回默认周期
  const loadCycles = async (): Promise<ObservationCycle | null> => {
    if (!stockCode) return null
    
    try {
      const response = await fetchCycles()
      if (response && Array.isArray(response) && response.length > 0) {
        setCycles(response)
        // 默认选择第一个周期（按照需求使用第一个，而不是当前活跃的）
        const defaultCycle = response[0]
        setSelectedCycle(defaultCycle)
        return defaultCycle
      }
    } catch (error) {
      console.error('加载周期列表失败:', error)
    }
    return null
  }

  // 加载跟踪数据（支持指定周期）
  const loadData = async (cycle?: ObservationCycle | null, showSuccessToast = true) => {
    if (!stockCode) {
      toast({
        title: "缺少股票代码",
        description: "请提供有效的股票代码",
        variant: "destructive",
        duration: 5000,
      })
      return
    }

    try {
      // 如果提供了周期参数，使用该周期；否则使用当前选中的周期
      const targetCycle = cycle !== undefined ? cycle : selectedCycle
      
      let apiResponse
      if (targetCycle === 'ALL') {
        apiResponse = await getStockDailyTracking(stockCode, { allCycles: true })
      } else if (targetCycle) {
        apiResponse = await getStockDailyTracking(stockCode, { 
          startDate: targetCycle.startDate, 
          endDate: targetCycle.endDate 
        })
      } else {
        apiResponse = await getStockDailyTracking(stockCode)
      }
      
      if (apiResponse && apiResponse.data) {
        setData(apiResponse.data)
        if (showSuccessToast) {
          toast({
            title: "数据加载成功",
            description: `获取到 ${apiResponse.data.name} 的跟踪数据`,
            duration: 3000,
          })
        }
      }
    } catch (error) {
      console.error('加载跟踪数据失败:', error)
      toast({
        title: "数据加载失败",
        description: "无法获取股票跟踪数据，请检查网络连接",
        variant: "destructive",
        duration: 5000,
      })
    } finally {
      setInitialLoading(false) // 初始加载完成
    }
  }

  // 初始化：先加载周期列表，再用第一个周期加载数据
  useEffect(() => {
    const initializeData = async () => {
      if (stockCode) {
        setInitialLoading(true)
        // 1. 先加载周期列表
        const defaultCycle = await loadCycles()
        // 2. 使用第一个周期的日期范围加载数据
        if (defaultCycle) {
          await loadData(defaultCycle, false) // 初始加载不显示成功提示
        } else {
          // 如果没有周期，则加载默认数据
          await loadData(null, false)
        }
      }
    }
    
    initializeData()
  }, [stockCode])

  // 选择周期后，重新加载数据（跳过初始加载）
  useEffect(() => {
    if (stockCode && selectedCycle && !initialLoading) {
      loadData(undefined, false) // 使用当前选中的周期，切换周期时不显示成功提示
    }
  }, [selectedCycle])

  // 计算收益状态
  const getReturnStatus = (value: number) => {
    if (value > 0) return { color: "text-success", icon: TrendingUp }
    if (value < 0) return { color: "text-destructive", icon: TrendingDown }
    return { color: "text-muted-foreground", icon: Activity }
  }

  const returnStatus = data ? getReturnStatus(data.summary.cumulativeReturn) : null

  // 如果没有股票代码，显示提示
  if (!stockCode) {
    return (
      <div className="min-h-screen bg-background flex items-center justify-center">
        <Card className="max-w-md">
          <CardContent className="flex flex-col items-center justify-center py-12">
            <AlertCircle className="w-12 h-12 text-muted-foreground mb-4" />
            <p className="text-lg font-semibold mb-2">缺少股票代码</p>
            <p className="text-sm text-muted-foreground mb-4 text-center">
              请通过主页面点击股票卡片访问跟踪页面
            </p>
            <Button onClick={() => router.push('/')} variant="outline">
              <ArrowLeft className="w-4 h-4 mr-2" />
              返回主页
            </Button>
          </CardContent>
        </Card>
      </div>
    )
  }

  return (
    <div className="min-h-screen bg-background">
      {/* Header */}
      <header className="border-b bg-card">
        <div className="container mx-auto px-4 py-4">
          <div className="flex items-center justify-between">
            <div className="flex items-center space-x-4">
              <Button
                variant="ghost"
                size="icon"
                onClick={() => router.back()}
              >
                <ArrowLeft className="w-5 h-5" />
              </Button>
              <div>
                <h1 className="text-2xl font-bold">股票每日跟踪</h1>
                <p className="text-sm text-muted-foreground">
                  {data ? `${data.name} (${data.code})` : stockCode}
                </p>
              </div>
            </div>

            <div className="flex items-center space-x-4">
              {/* 观察周期选择器 */}
              {cycles.length > 0 && selectedCycle && (
                <Select 
                  value={selectedCycle === 'ALL' ? 'ALL' : selectedCycle.startDate} 
                  onValueChange={(value) => {
                    if (value === 'ALL') {
                      setSelectedCycle('ALL')
                    } else {
                      const cycle = cycles.find(c => c.startDate === value)
                      if (cycle) setSelectedCycle(cycle)
                    }
                  }}
                >
                  <SelectTrigger className="w-[300px]">
                    <SelectValue placeholder="选择周期">
                      <div className="flex items-center gap-2">
                        <Calendar className="w-3.5 h-3.5 text-muted-foreground shrink-0" />
                        {selectedCycle === 'ALL' ? (
                          <span className="text-sm font-medium">全部周期</span>
                        ) : (
                          <>
                            <span className="text-sm">
                              {selectedCycle.startDate} ~ {selectedCycle.endDate}
                            </span>
                            <Badge variant="outline" className="text-xs px-1.5 py-0 shrink-0">
                              {selectedCycle.daysCount}天
                            </Badge>
                          </>
                        )}
                      </div>
                    </SelectValue>
                  </SelectTrigger>
                  <SelectContent className="w-[380px]">
                    {/* 全部周期选项 */}
                    <SelectItem value="ALL" className="cursor-pointer">
                      <div className="flex items-center justify-between w-full gap-3">
                        <span className="text-sm font-medium">
                          全部周期
                        </span>
                        <Badge variant="outline" className="text-xs px-2 py-0.5">
                          查看全部
                        </Badge>
                      </div>
                    </SelectItem>
                    
                    {/* 分隔线 */}
                    <div className="h-px bg-border my-1" />
                    
                    {/* 各个周期选项 */}
                    {cycles.map((cycle) => (
                      <SelectItem key={cycle.startDate} value={cycle.startDate} className="cursor-pointer">
                        <div className="flex items-center justify-between w-full gap-3">
                          <span className="text-sm font-medium">
                            {cycle.startDate} ~ {cycle.endDate}
                          </span>
                          <div className="flex items-center gap-1.5 shrink-0">
                            <Badge variant="outline" className="text-xs px-2 py-0.5">
                              {cycle.daysCount}天
                            </Badge>
                            <Badge 
                              variant={cycle.isCurrent ? "default" : "secondary"} 
                              className="text-xs px-2 py-0.5"
                            >
                              {cycle.status}
                            </Badge>
                          </div>
                        </div>
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              )}

              <Button
                onClick={async () => await loadData(undefined, true)}
                disabled={isLoading}
                size="sm"
                className="bg-accent hover:bg-accent/90"
              >
                <RefreshCw className={cn("w-4 h-4 mr-2", isLoading && "animate-spin")} />
                刷新数据
              </Button>

              {/* 主题切换和用户导航 */}
              <div className="flex items-center space-x-2">
                <ThemeSwitch />
                <UserNav />
              </div>
            </div>
          </div>
        </div>
      </header>

      <main className="container mx-auto px-4 py-6">
        {(isLoading || initialLoading) && !data ? (
          // 加载骨架屏（初始加载或刷新中）
          <div className="space-y-6">
            <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
              {Array.from({ length: 4 }).map((_, i) => (
                <Card key={i}>
                  <CardContent className="p-4">
                    <Skeleton className="h-4 w-20 mb-2" />
                    <Skeleton className="h-8 w-24 mb-2" />
                    <Skeleton className="h-3 w-16" />
                  </CardContent>
                </Card>
              ))}
            </div>
            <Card>
              <CardContent className="p-6">
                <Skeleton className="h-6 w-32 mb-4" />
                <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
                  {Array.from({ length: 8 }).map((_, i) => (
                    <Skeleton key={i} className="h-16 w-full" />
                  ))}
                </div>
              </CardContent>
            </Card>
          </div>
        ) : data ? (
          <div className="space-y-6">
            {/* 顶部统计卡片 */}
            <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
              <StatCard
                icon={returnStatus!.icon}
                title="累计收益"
                value={formatPercent(data.summary.cumulativeReturn)}
                description={`观察期: ${data.observationPeriod}天`}
                valueColor={returnStatus!.color}
              />
              <StatCard
                icon={Calendar}
                title="持仓天数"
                value={data.summary.totalDays}
                description={data.summary.observationProgress ? `进度: ${data.summary.observationProgress}` : undefined}
              />
              <StatCard
                icon={Target}
                title="胜率"
                value={formatPercent(data.summary.winRate, false)}
                description={data.summary.winDays && data.summary.lossDays ? `${data.summary.winDays}胜/${data.summary.lossDays}负` : undefined}
              />
              <StatCard
                icon={Activity}
                title="平均信号强度"
                value={data.summary.avgSignalStrength?.toFixed(2) ?? '--'}
                description={data.summary.marketOutperformDays ? `跑赢大盘: ${data.summary.marketOutperformDays}天` : undefined}
              />
            </div>

            {/* 股票基本信息卡 */}
            <Card>
              <CardHeader>
                <div className="flex items-center justify-between">
                  <div>
                    <CardTitle>{data.name}</CardTitle>
                    <CardDescription>{data.code}</CardDescription>
                  </div>
                  <Badge variant={data.currentStatus === "观察中" ? "default" : "secondary"} className="text-sm">
                    {data.currentStatus}
                  </Badge>
                </div>
              </CardHeader>
              <CardContent>
                <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
                  <div>
                    <p className="text-sm text-muted-foreground mb-1">首次买入</p>
                    <p className="font-medium">{data.firstBuyDate}</p>
                  </div>
                  {data.summary.bestDayReturn !== undefined && (
                    <div>
                      <p className="text-sm text-muted-foreground mb-1">最佳收益</p>
                      <p className="font-medium font-mono text-success">
                        {formatPercent(data.summary.bestDayReturn)}
                      </p>
                    </div>
                  )}
                  {data.summary.worstDayReturn !== undefined && (
                    <div>
                      <p className="text-sm text-muted-foreground mb-1">最差收益</p>
                      <p className="font-medium font-mono text-destructive">
                        {formatPercent(data.summary.worstDayReturn)}
                      </p>
                    </div>
                  )}
                  {data.summary.avgVolume !== undefined && (
                    <div>
                      <p className="text-sm text-muted-foreground mb-1">平均成交量</p>
                      <p className="font-medium font-mono">
                        {formatVolume(data.summary.avgVolume)}
                      </p>
                    </div>
                  )}
                </div>
              </CardContent>
            </Card>

            {/* 信号分布统计 */}
            {data.summary.signalDistribution && data.summary.signalDistribution.length > 0 && (
              <SignalDistributionCard signals={data.summary.signalDistribution} />
            )}

            {/* 每日记录列表 */}
            <div>
              <div className="flex items-center justify-between mb-4">
                <h2 className="text-xl font-semibold">每日交易记录</h2>
                <Badge variant="outline" className="text-sm">
                  共 {data.dailyRecords.length} 条记录
                </Badge>
              </div>

              <div className="space-y-3">
                {data.dailyRecords.map((record, index) => (
                  <DailyRecordCard key={record.date} record={record} index={index} />
                ))}
              </div>
            </div>
          </div>
        ) : (
          // 空状态
          <Card>
            <CardContent className="flex flex-col items-center justify-center py-12">
              <AlertCircle className="w-12 h-12 text-muted-foreground mb-4" />
              <p className="text-lg font-semibold mb-2">暂无数据</p>
              <p className="text-sm text-muted-foreground mb-4">
                无法获取该股票的跟踪数据
              </p>
              <Button onClick={async () => await loadData(undefined, true)} variant="outline">
                <RefreshCw className="w-4 h-4 mr-2" />
                重试
              </Button>
            </CardContent>
          </Card>
        )}
      </main>
    </div>
  )
}

